<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="600px"
    :before-close="handleClose"
    :append-to-body="true"
    center
  >
    <el-row :gutter="24">
      <el-form status-icon label-width="80px">
        <el-form-item label="用户名">
          <el-input
            type="username"
            v-model="userFrom.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            type="password"
            v-model="userFrom.password"
            autocomplete="off"
            @keyup.enter.native="submitform"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="submitform">登录</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { Message } from "element-ui";
import { login, userInfo } from "@/api/api.js";
import { mapMutations,mapGetters } from "vuex";
export default {
  name: "login",
  data() {
    return {
      dialogVisible: false,
      userFrom: {
        phone: "",
        password: "",
      },
    };
  },
  computed: {
    ...mapGetters(["isLogin", "userInfo"]),
  },
  methods: {
    ...mapMutations(["setLogin", "setUserInfo"]),
    open() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.userFrom = {};
      this.dialogVisible = false;
    },
    // 提交表单登录
    submitform() {
      let that = this;
      if (!that.userFrom.password) {
        Message.error({
          message: "请输入密码！",
        });
      } else {
        //  let password =  this.$md5(this.userFrom.md5_password)
        //  this.userFrom.md5_password = password
        login(that.userFrom).then((res) => {
          if (res.data.code == 502) {
            return Message.error({
              message: "密码输入错误",
            });
          } else if (res.data.code == 200) {
            Message.success({
              message: "登录成功！",
            });
            this.getUserInfo(res.data.profile.userId);
            window.sessionStorage.setItem("token", res.data.token);
            window.sessionStorage.setItem("cookie", res.data.cookie);
            window.sessionStorage.setItem("isLogin", true);
            that.handleClose();
          }
        });
      }
    },
    // 获取用户信息
    getUserInfo(uid) {
      userInfo({ uid: uid }).then((res) => {
        console.log(res);
        window.sessionStorage.setItem( "userInfo", JSON.stringify(res.data.profile));
        this.setLogin(true);
        this.setUserInfo(res.data.profile);
      });
    },
  },
};
</script>

<style lang='less' scoped>
.el-col {
  margin-bottom: 20px;

  .el-input {
    font-family: "hmR";
    font-size: 14px;
    border-left: none;
  }
}
</style>